package com.zxkj.ssm.weixin.shop.basic;
import com.zxkj.ssm.weixin.shop.exception.WxErrorException;
import com.zxkj.ssm.weixin.shop.http.executor.RequestExecutor;
import com.zxkj.ssm.weixin.shop.http.executor.SimpPostNameValuePairRequestExecutor;
import com.zxkj.ssm.weixin.shop.http.executor.SimpleGetRequestExecutor;
import com.zxkj.ssm.weixin.shop.http.executor.SimplePostRequestExecutor;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.Map;

/**
 *@Author cxy
 *@Date 2018/7/11 9:25
 *@Description  实现了简单的 http 请求
 *@Version
 */
@Component
public class WeixinServiceImpl implements WeixinService {
    private CloseableHttpClient httpClient;
    /*public CloseableHttpClient getHttpClient() {//本身由 DefaultApacheHttpClientBuilder  进行获取  暂时不用
        return httpClient;
    }*/
    public CloseableHttpClient getHttpClient() {
        return 	this.httpClient= HttpClients.createDefault();
    }
    @Override
    public String post(String url, String postData) throws WxErrorException {

        return execute(new SimplePostRequestExecutor(), url, postData);
    }

    public String post(String url, Map<?,?> map) throws WxErrorException{
        return execute(new SimpPostNameValuePairRequestExecutor(),url,map);
    }

    @Override
    public String get(String url, String queryParam) throws WxErrorException {
        return 	executeHttpClient(new SimpleGetRequestExecutor(), url, queryParam);
    }
    @Override
    public <T, E> T execute(RequestExecutor<T, E> executor, String url, E data)
            throws WxErrorException {
        return executeHttpClient(executor, url, data);
    }

    /**
     * 各种执行的通用入口进行异步控制
     * @param executor
     * @param url
     * @param data
     * @return
     * @throws WxErrorException
     */

    protected synchronized <T, E> T executeHttpClient(RequestExecutor<T, E> executor, String url, E data) throws WxErrorException{
        try {
            return executor.execute(getHttpClient(), null, url, data);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
